/**
 * 
 */
package biz.innovasoft.ndb;

import java.io.Serializable;
import java.util.List;

import biz.innovasoft.ndb.query.Tuple;

/**
 * 
 * @author Diego Miranda
 *
 */
public class UpdateHelper implements Serializable {

	private static final long serialVersionUID = -4757833261740986873L;

	private GenericRepository repository;
	
	public UpdateHelper (GenericRepository repository) {
		this.repository = repository;
	}
	
	public Object update (Long oid, Object object) throws RepositoryException {
		return update (oid, object, true);
	}
	
	public Object update(Long oid, Object object, boolean index)
			throws RepositoryException {
		if (!repository.getObjects().containsKey(oid)) {
			throw new RepositoryException(
					"Trying to update an object with an inexistent key. OID: "
							+ oid);
		}
		Object old = repository.getByOId(oid);
		repository.getObjects().put(oid, object);
		if ( index ) {
			repository.reindexObject (oid, object);
		}
		return old;
	}

	public void update (List<Tuple> tuples) throws RepositoryException {
		for (Tuple tuple : tuples ) {
			update (tuple.oid, tuple.value, false);
		}
		for (Tuple tuple : tuples ) {
			repository.indexObject(tuple.oid, tuple.value);
		}
	}
	
}
